#ifdef GL_FRAGMENT_PRECISION_HIGH
   // Default precision
   precision highp float;
#else
   precision mediump float;
#endif


uniform sampler2D noise;
uniform samplerCube envMap;

uniform float time;
uniform vec4  color;
uniform float fadeExp;
uniform float fadeBias;
uniform float noiseSpeed;
uniform float waveSpeed;

varying vec3 vTexCoord;
varying vec3 vNormal;
varying vec3 vViewVec;


void main(void)
{
   vec3 tcoord = vTexCoord;
   tcoord.x += waveSpeed + cos(time)*0.5;// cos(time)*0.5-0.5;//abs(cos(waveSpeed  + time)*1);
   tcoord.y += noiseSpeed + time;//abs(sin(noiseSpeed + time)*0.9);

	vec4 noisy = texture2D(noise, tcoord.xy, fadeBias);


   // Signed noise 
   //vec3 bump = 2.0 * noisy.xyz - 1.0;
   //bump.xyz *= 0.2;
   vec3 bump = 0.4 *noisy.xyz - 0.2;
   
   // Make sure the normal always points upwards
   bump.z = 0.8 * abs(bump.z) +0.5;
   
   // Offset the surface normal with the bump
   bump = (vNormal + bump);
   
   // Find the reflection vector
   vec3 reflVec = reflect(vViewVec, bump);
  
  
   vec4 refl = textureCube(envMap, reflVec.xyz);
   
   float lrp = 1- (dot(-normalize(vViewVec), bump))*0.9;

	float ay = abs(vTexCoord.x);
	float ax = abs(vTexCoord.y);
	vec4 edge;
	if (ay >= -2*ax+0.1725 || ay >= 0.09)
		edge = vec4(0.2, 0.2,0.2,0.0) ;
	else
		edge = vec4(0.0,0.0,0.0,1.0);

   // Interpolate between the water color and reflection
   gl_FragColor = mix(color, refl, clamp(fadeBias + pow(lrp, fadeExp),0.0, 0.5)) + edge;
}